namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Web.Mvc;
    using System.Web.Routing;
    using SimpleWebServices.Models;
    using SimpleWebServices.Web.Routing;

    [InternalServerError]
    [Allow(Methods = "GET, HEAD, OPTIONS")]
    [ContentMD5]
    public sealed class TenantStyleSheetController : Controller, IRegisterRoutes
    {
        public void Register(RouteCollection routes)
        {
            if (null == routes)
            {
                throw new ArgumentNullException("routes");
            }

            routes.Add(new TenantStyleSheetRoute());
        }

        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "ASP.NET MVC requires the method to be an instance member.")]
        public ActionResult CssRepresentation()
        {
            ActionResult result = null;

            Tenant tenant = Tenant.Current;
            if (null != tenant)
            {
                foreach (StyleSheet stylesheet in tenant.StyleSheets.Where(x => string.Equals(x.Href, HttpContextFactory.Current.Request.Path, StringComparison.OrdinalIgnoreCase)))
                {
                    if (null != stylesheet.Imports && 0 != stylesheet.Imports.Count)
                    {
                        result = new StyleSheetResult
                        {
                            Content = stylesheet.ToString()
                        };
                        break;
                    }
                }
            }

            return result ?? new NotFoundResult();
        }
    }
}